using System;
using System.Timers;

namespace Voodoo.Sauce.Internal.Analytics
{
	internal class AnalyticsSessionManager
	{
		private const string TAG = "Analytics - SessionHelper";

		private const string PlayerPrefSessionCountKey = "VOODOO_ANALYTICS_SESSION_COUNT";

		private DateTime _lastEventCreationDate = DateTime.Now;

		private Timer _sessionLengthTimer;

		private int _sessionIdRenewalIntervalInSeconds;

		private static AnalyticsSessionManager _instance;

		internal SessionInfo SessionInfo { get; } = new SessionInfo();


		internal event Action<SessionInfo> OnNewSession;

		internal static AnalyticsSessionManager Instance()
		{
			if (_instance == null)
			{
				_instance = new AnalyticsSessionManager();
			}
			return _instance;
		}

		internal void Init()
		{
			if (_sessionLengthTimer == null)
			{
				_sessionLengthTimer = new Timer(1000.0)
				{
					Enabled = true,
					AutoReset = true
				};
				_sessionLengthTimer.Elapsed += delegate
				{
					SessionInfo.length++;
				};
				_sessionLengthTimer.Start();
			}
			if (!NintendoPlayerPrefs.HasKey("VOODOO_ANALYTICS_SESSION_COUNT"))
			{
				NintendoPlayerPrefs.SetInt("VOODOO_ANALYTICS_SESSION_COUNT", AnalyticsStorageHelper.Instance.GetAppLaunchCount());
			}
			else
			{
				IncrementSessionCount();
			}
			SessionInfo.count = NintendoPlayerPrefs.GetInt("VOODOO_ANALYTICS_SESSION_COUNT", 1);
			ResetSession();
			RefreshCreationDate();
		}

		internal void OnNewEvent()
		{
			if (_lastEventCreationDate.AddSeconds(_sessionIdRenewalIntervalInSeconds) < DateTime.Now)
			{
				Update();
			}
			RefreshCreationDate();
		}

		private void Update()
		{
			ResetSession();
			IncrementSessionCount();
			RefreshCreationDate();
		}

		private void ResetSession()
		{
			SessionInfo.id = Guid.NewGuid().ToString();
			SessionInfo.length = 0;
			this.OnNewSession?.Invoke(SessionInfo);
			VoodooLog.LogDebug(Module.ANALYTICS, "Analytics - SessionHelper", "New session id: " + SessionInfo.id);
		}

		private void IncrementSessionCount()
		{
			SessionInfo.count = NintendoPlayerPrefs.GetInt("VOODOO_ANALYTICS_SESSION_COUNT", 1) + 1;
			NintendoPlayerPrefs.SetInt("VOODOO_ANALYTICS_SESSION_COUNT", SessionInfo.count);
			VoodooLog.LogDebug(Module.ANALYTICS, "Analytics - SessionHelper", "Session count incremented to: " + SessionInfo.count);
		}

		private void RefreshCreationDate()
		{
			_lastEventCreationDate = DateTime.Now;
		}

		internal void StopTimer()
		{
			_sessionLengthTimer?.Stop();
		}
	}
}
